﻿using InteractiveDataDisplay.WPF;
using LiveCharts.Wpf;
using LiveCharts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfSnqkGasAnalysis.IBusiness_impl;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// 首页
    /// </summary>
    public partial class PageHome : Page
    {
        //private static int isRegister = 0;

        public PageHome()
        {
            InitializeComponent();

            //if (isRegister == 0)
            //{
            //   // MainWindow.RefreshPageHome += MainWindow_RefreshPageHome;
            //    isRegister = 1;
            //}
        }

        //private void MainWindow_RefreshPageHome(object? sender, EventArgs e)
        //{
        //    Page_Loaded(sender, new RoutedEventArgs() { RoutedEvent = Mouse.MouseUpEvent });           
        //}

        Gas_analysisBusiness gas_AnalysisBusiness = new Gas_analysisBusiness();
        CleanGasBusiness cleanGasBusiness = new CleanGasBusiness();
        TeshuBusiness teshuBusiness = new TeshuBusiness();
        WaterPointBusiness waterPointBusiness = new WaterPointBusiness();
        SulfurBusiness sulfurBusiness = new SulfurBusiness();
        SourceDictBusiness sourceDictBusiness = new SourceDictBusiness();

        /// <summary>
        /// 曲线颜色
        /// </summary>
        readonly static SolidColorBrush lineColor = new SolidColorBrush(Color.FromRgb(11, 22, 178));

        /// <summary>
        /// 曲线粗细
        /// </summary>
        const double lineWidth = 4d;

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (GetLoginHelpter.CurrentLoginUser().Role_id == "录入人"
                && GetLoginHelpter.CurrentLoginUser().User_account != CommonConfig.SupperUserAccount)
            {
                //全部 模块隐藏
                ModelVisibi(txt_gas_waitNum);
                ModelVisibi(txt_clean_gas_waitNum);
                ModelVisibi(txt_teshu_waitNum);
                ModelVisibi(txt_water_num);
                ModelVisibi(txt_s_num);

            }

            //查询待办记录数量
            Task.Run(() =>
            {
                Gas_analysis gas_Analysis = new Gas_analysis();
                var gasPage = gas_AnalysisBusiness.Page(gas_Analysis, 1, 1);
                this.Dispatcher.InvokeAsync(() =>
                {
                    txt_gas_waitNum.Text = gasPage.Total.ToString();//天然气
                    if (gasPage.Total == 0)
                    {
                        ModelVisibi(txt_gas_waitNum);
                    }
                });
            });


            //净化气，待处理数
            Task.Run(() =>
            {
                var pageClean = cleanGasBusiness.GetPage(new Clean_gas(), 1, 1);
                this.Dispatcher.InvokeAsync(() =>
                {
                    txt_clean_gas_waitNum.Text = pageClean.Total.ToString();
                    if (pageClean.Total == 0)
                    {
                        ModelVisibi(txt_clean_gas_waitNum);
                    }
                });
            });


            //特殊报告，待处理数
            Task.Run(() =>
            {
                var teshuPage = teshuBusiness.Page(new Teshu_gas(), 1, 1);
                this.Dispatcher.InvokeAsync(() =>
                {
                    txt_teshu_waitNum.Text = teshuPage.Total.ToString();
                    if (teshuPage.Total == 0)
                    {
                        ModelVisibi(txt_teshu_waitNum);
                    }
                });
            });


            //水露点，待处理数
            Task.Run(() =>
            {
                var waterPage = waterPointBusiness.Page(new Water_point(), 1, 1);
                this.Dispatcher.InvokeAsync(() =>
                {
                    txt_water_num.Text = waterPage.Total.ToString();
                    if (waterPage.Total == 0)
                    {
                        ModelVisibi(txt_water_num);
                    }
                });
            });


            //有机硫，待处理数
            Task.Run(() =>
            {
                var suPage = sulfurBusiness.GetPage(new Organic_sulfur(), 1, 1);
                this.Dispatcher.InvokeAsync(() =>
                {
                    txt_s_num.Text = suPage.Total.ToString();
                    if (suPage.Total == 0)
                    {
                        ModelVisibi(txt_s_num);
                    }
                });
            });

            //注释时间：2023-1-30 14:34:17
            ////加载曲线图         
            //PointCollection points = new PointCollection();

            //List<double> xList = new List<double>();
            //List<double> yList = new List<double>();
            //for (int i = 0; i < 100; i++)
            //{
            //    //points.Add(new Point(i, Math.Sin(i)));
            //    xList.Add(i);
            //    //yList.Add(Math.Sin(i * 0.01));
            //    yList.Add(i + 1);
            //}

            //var lg = new LineGraph();
            //lines.Children.Add(lg);
            //lg.Stroke = lineColor;
            ////lg.Description = String.Format("图表1" );
            //lg.StrokeThickness = lineWidth;
            //lg.Plot(xList, yList);
            ////lg.Points = points;
            //lg.MouseMove += Lg_MouseMove;
            ////lg.PlotTransformChanged += Lg_PlotTransformChanged;//无效



            //样品类别
            var cateList = sourceDictBusiness.GetListByGroup("cate");
            //cateList.Add(new Source_dict() { Id = 112201, Item_name = "水露点" });
            //cateList.Add(new Source_dict() { Id = 112202, Item_name = "净化气" });
            //cateList.Add(new Source_dict() { Id = 112203, Item_name = "有机硫" });

            cmbSampleCate.ItemsSource = cateList;
            cmbSampleCate.DisplayMemberPath = "Item_name";
            cmbSampleCate.SelectedValuePath = "Id";

            // cmbSampleCate.SelectionChanged += CmbSampleCate_SelectionChanged;

            //天然气指标
            var gasZbList = MyConfigReader.GetConfigList("gas_zhibiao_list");
            foreach (var item in gasZbList)
            {
                MakeZb(item);
            }
            date_1.SelectedDate = DateTime.Now.AddDays(-365);
            date_2.SelectedDate = DateTime.Now.AddDays(1);

            // 样品数 。添加时间：2023-1-3 09:29:11
            Task.Run(() =>
            {
                //开发样品数 sampKaifa
                int kaifa = gas_AnalysisBusiness.GetCateCount("1");
                //汇管样品数
                int huiGuan = gas_AnalysisBusiness.GetCateCount("4");
                //勘探样品数
                int kantan = gas_AnalysisBusiness.GetCateCount("3");
                //水露点数量
                int _waterCount = waterPointBusiness.GetCount();
                //净化气数量
                int _cleanCount = cleanGasBusiness.GetCleanCount();

                //其他数量
                int _otherCount = cleanGasBusiness.GetCleanCount();

                //总数
                int total = kaifa + huiGuan + kantan + _waterCount + _cleanCount + _otherCount;
                this.Dispatcher.InvokeAsync(() =>
                {
                    sampKaifa.Text = kaifa.ToString();
                    sampHuiGuan.Text = huiGuan.ToString();
                    sampKantan.Text = kantan.ToString();
                    waterCount.Text = _waterCount.ToString();
                    cleanCount.Text = _cleanCount.ToString();
                    otherCount.Text = _otherCount.ToString();
                    totalSamp.Text = total.ToString();

                    //进度条
                    sampKaifa_pross.Value = (double)Math.Round((decimal)kaifa / total * 100, 1);
                    sampKaifaPercent.Text = sampKaifa_pross.Value + "%";

                    sampHuiGuan_pross.Value = (double)Math.Round((decimal)huiGuan / total * 100, 1);
                    sampHuiGuanPercent.Text = sampHuiGuan_pross.Value + "%";

                    sampKantan_pross.Value = (double)Math.Round((decimal)kantan / total * 100, 1);
                    sampKantanPercent.Text = sampKantan_pross.Value + "%";

                    water_progress.Value = (double)Math.Round((decimal)_waterCount / total * 100, 1);
                    waterPercent.Text = water_progress.Value + "%";

                    cleanCount_progress.Value = (double)Math.Round((decimal)_cleanCount / total * 100, 1);
                    cleanCountPercent.Text = cleanCount_progress.Value + "%";

                    other_progress.Value = (double)Math.Round((decimal)_otherCount / total * 100, 1);
                    otherPercent.Text = other_progress.Value + "%";
                });



            });
        }



        /// <summary>
        /// 14个，颜色列表，用于随机
        /// </summary>
        List<Brush> ColorList = new List<Brush>() {
             Brushes.Purple,
             Brushes.Blue,
             Brushes.Brown,
             Brushes.MidnightBlue,
             Brushes.Aquamarine,
             Brushes.CadetBlue,
             Brushes.Chartreuse,
             Brushes.CornflowerBlue,
             Brushes.DarkBlue,
             Brushes.Fuchsia,
             Brushes.ForestGreen,
             Brushes.HotPink,
             Brushes.RoyalBlue,
             Brushes.Orange,
             Brushes.Magenta
        };

        //private void CmbSampleCate_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        ////样品类别
        //ComboBox comboBox = sender as ComboBox;
        //var zb = comboBox.SelectedValue.ToString();
        ////ShowAlertHelpter.ShowAlert(km.ToString());

        ////string arr = "112201;112202;112203"; //非天然气模块的
        ////if (!arr.Contains(zb))
        ////{
        ////    //天然气指标
        ////    var gasZbList = MyConfigReader.GetConfigList("gas_zhibiao_list");
        ////    foreach (var item in gasZbList)
        ////    {
        ////        MakeZb(item);
        ////    }
        ////}
        ////else if(zb.Equals("112201"))//水露点
        ////{
        ////    //水露点
        ////    //净化气
        ////    //有机硫
        ////    MakeZb(item);
        ////}
        //}

        /// <summary>
        /// 已经生过的颜色
        /// </summary>
        /// 创建时间：2023-1-4 18:10:32
        List<int> colorHaved = new List<int>();

        /// <summary>
        /// 生成指标按钮
        /// </summary>
        /// <param name="zbName">指标</param>
        /// 创建时间：2022-12-30 17:09:08。作者：王浩力
        private void MakeZb(string zbName)
        {
            Task.Run(() =>
            {
                //颜色下标
                Random random = new Random();
                int index = random.Next(0, ColorList.Count - 1);
                while (colorHaved.Contains(index))
                {
                    index = random.Next(0, ColorList.Count - 1);
                }
                colorHaved.Add(index);

                this.Dispatcher.InvokeAsync(() =>
                {
                    //加载指标列表
                    Border border = new Border();
                    border.Style = (Style)gridWai.FindResource("BorderHome02");
                    DockPanel dockPanel = new DockPanel();
                    Ellipse ellipse = new Ellipse();
                    ellipse.Fill = ColorList[index]; //new SolidColorBrush(Color.FromArgb());
                    ellipse.ToolTip = ellipse.Fill.ToString();
                    Button button = new Button();
                    button.Content = zbName;
                    button.Click += Button_Click1;
                    dockPanel.Children.Add(ellipse);
                    dockPanel.Children.Add(button);
                    border.Child = dockPanel;

                    WrapPanel_zhibiao.Children.Add(border);
                });
            });
        }

        /*   换了插件，修改时间：2023-1-30 14:29:48
        //点击指标触发，加载指标曲线图  //创建时间：2022-12-30 17:02:22。
        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            ShowAlertHelpter.ShowAlert("指标=" + button.Content);

            //加载曲线数据
            string cate = Convert.ToString(cmbSampleCate.SelectedValue);
            string date1 = date_1.Text.ToString();      //开始日期
            string date2 = date_2.Text.ToString();      //开始日期
            string zb = button.Content.ToString();//指标
            string well = txtWell.Text.Trim();//井号
            Task.Run(() =>
            {
                var result = gas_AnalysisBusiness.GetZbPoints(zb, cate, date1, date2, well);
                if (result.Code != (int)ResultCode.Success)
                {
                    ShowAlertHelpter.ShowAlert(result.Msg);
                }
                if (result.Data == null || result.Data.Count == 0)
                {
                    ShowAlertHelpter.ShowAlert("没有数据");
                    return;
                }

                this.Dispatcher.Invoke(() =>
                {
                    //修改时间：2023-1-18 11:19:47。重置图表刻度，让线充满
                    //plotter.IsXAxisReversed = false;//从左往右，0在左边
                    //plotter.IsYAxisReversed = true;
                    plotter.IsAutoFitEnabled = true;
                    //plotter.LegendVisibility = Visibility.Visible;

                    PointCollection points = new PointCollection();
                    int index = 0;

                    foreach (var item in result.Data)
                    {
                        points.Add(new Point(index, item.Y));
                        index++;
                    }

                    //plotter.UpdateLayout();
                    plotter.Title = zb + "趋势图";
                    var lg = new LineGraph();
                    lg.Stroke = lineColor;
                    //lg.Description = String.Format("图表1" );
                    lg.StrokeThickness = lineWidth;
                    // lg.Plot(x, x.Select(v => Math.Sin(v *0.01)).ToArray());
                    lg.Points = points;
                    lines.Children.Clear();
                    //lines.Measure(lines.RenderSize);
                    //lines.UpdateDefaultStyle();
                    //lines.UpdateLayout();

                    //lg.TouchMove
                    //lg.TouchUp += Lg_TouchUp;
                    //lg.MouseUp += Lg_MouseUp;
                    lg.MouseMove += Lg_MouseMove;

                    //lines.Cursor= Cursors.
                    //lines.TouchMove += Lines_TouchMove;
                    //lines.TouchUp += Lines_TouchUp;
                    //lines.PreviewMouseMove += Lines_PreviewMouseMove;
                    //lines.MouseMove += Lines_MouseMove;//有效

                    lines.Children.Add(lg);

                });
            });
        }
        */

        //点击指标触发，加载指标曲线图  //创建时间：2023-1-30 14:30:07
        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            ShowAlertHelpter.ShowAlert("指标=" + button.Content);

            //加载曲线数据
            string cate = Convert.ToString(cmbSampleCate.SelectedValue);
            string date1 = date_1.Text.ToString();      //开始日期
            string date2 = date_2.Text.ToString();      //开始日期
            string zb = button.Content.ToString();//指标
            string well = txtWell.Text.Trim();//井号
            Task.Run(() =>
            {
                var result = gas_AnalysisBusiness.GetZbPoints(zb, cate, date1, date2, well);
                if (result.Code != (int)ResultCode.Success)
                {
                    ShowAlertHelpter.ShowAlert(result.Msg);
                }
                if (result.Data == null || result.Data.Count == 0)
                {
                    ShowAlertHelpter.ShowAlert("没有数据");
                    return;
                }

                this.Dispatcher.Invoke(() =>
                {
                    var yList = new ChartValues<double>();
                    foreach (var item in result.Data)
                    {
                        double y = Math.Round(item.Y, 4);
                        yList.Add(y);
                    }
                    //图表填充值
                    var line = new LineSeries
                    {
                        Title = zb + "趋势",
                        LineSmoothness=0, //曲线是否圆滑。如为 1则圆滑曲线，为 0则不圆滑，为折线。
                        Values = yList
                    };

                    ////X轴
                    //List<string> x_list = new List<string>();
                    //for (int i = 0; i < result.Data.Count; i++)
                    //{
                    //    x_list.Add(i.ToString());
                    //}
                    //this.chart9.AxisX.Clear();
                    //this.chart9.AxisX.Add(new LiveCharts.Wpf.Axis() {Labels= x_list });

                    this.chart9.Series.Clear();
                    this.chart9.Series.Add(line);
                });
            });
        }

        //private void Lg_MouseMove(object sender, MouseEventArgs e)
        //{
        //LineGraph line = sender as LineGraph;
        //var y = line.PlotHeight;
        //ShowAlertHelpter.ShowAlert(y.ToString());

        //var point = e.GetPosition(line);
        //var point33 = line.TranslatePoint(point, line);
        //var polotX = line.XDataTransform.DataToPlot(point.X);


        //var point22 = plotter.TranslatePoint(point, line);

        //line.TranslatePoint()


        //  }


        //private void Lines_MouseMove(object sender, MouseEventArgs e)
        //{
        //    throw new NotImplementedException();
        //}




        /// <summary>
        /// 设置模块隐藏
        /// </summary>
        /// <param name="textBlock"></param>
        private void ModelVisibi(TextBlock textBlock)
        {
            var dockpanelGAS = ((((textBlock.Parent) as FrameworkElement).Parent) as FrameworkElement).Parent as UIElement;
            dockpanelGAS.Visibility = Visibility.Collapsed;
        }

        //去处理  //创建时间：2022-12-29 23:07:36
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (Convert.ToString(button.Tag) == "gas")
            {
                //导航到：天然气模块
                //MainWindow.Instance.frameMain.Source=               
                MainWindow.Instance.K3.RaiseEvent(
                        new System.Windows.Input.MouseButtonEventArgs(
                        Mouse.PrimaryDevice, 1, MouseButton.Left)
                        {
                            RoutedEvent = MouseLeftButtonUpEvent
                        }
                    );
            }
            else if (Convert.ToString(button.Tag) == "clean")  //净化气
            {
                MainWindow.Instance.K4.RaiseEvent(
                     new System.Windows.Input.MouseButtonEventArgs(
                     Mouse.PrimaryDevice, 1, MouseButton.Left)
                     {
                         RoutedEvent = MouseLeftButtonUpEvent
                     }
                 );
            }
            else if (Convert.ToString(button.Tag) == "teshu")  //特殊报告
            {
                MainWindow.Instance.K5.RaiseEvent(
                     new System.Windows.Input.MouseButtonEventArgs(
                     Mouse.PrimaryDevice, 1, MouseButton.Left)
                     {
                         RoutedEvent = MouseLeftButtonUpEvent
                     }
                 );
            }
            else if (Convert.ToString(button.Tag) == "water")  //水露点
            {
                MainWindow.Instance.K6.RaiseEvent(
                     new System.Windows.Input.MouseButtonEventArgs(
                     Mouse.PrimaryDevice, 1, MouseButton.Left)
                     {
                         RoutedEvent = MouseLeftButtonUpEvent
                     }
                 );
            }
            else if (Convert.ToString(button.Tag) == "sliu")  //有机硫
            {
                MainWindow.Instance.K61.RaiseEvent(
                     new System.Windows.Input.MouseButtonEventArgs(
                     Mouse.PrimaryDevice, 1, MouseButton.Left)
                     {
                         RoutedEvent = MouseLeftButtonUpEvent
                     }
                 );
            }

            //按钮事件结束
        }



    }
}
